package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.zaxxer.hikari.HikariDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    public Configuration configuration;

    public XMLConfigBuilder() {
        configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream inputStream) throws Exception {

        Properties properties = new Properties();

        Document document = new SAXReader().read(inputStream);

        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        list.stream().forEach(element -> {
            properties.setProperty(element.attributeValue("name"), element.attributeValue("value"));
        });

        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        dataSource.setDriverClassName(properties.getProperty("driverClass"));
        configuration.setDataSource(dataSource);
        List<Element> mappers = rootElement.selectNodes("//mapper");
        mappers.stream().forEach(mapper -> {
            String path = mapper.attributeValue("resource");
            InputStream in = Resources.getResourceAsStream(path);
            XMLMapperBuilder builder = new XMLMapperBuilder(configuration);

            try {
                builder.parse(in);
            } catch (DocumentException e) {
                e.printStackTrace();
            }


        });

        return configuration;
    }
}
